﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO.IsolatedStorage;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

namespace ICeFramework.DataAccess.SettingsStorage
{
    public static class SqlDataStorage
    {
        //private static string settingsFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".dat";

        #region public static SqlDataStorageEntity Load(string name)
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static SqlDataStorageEntity Load(string name)
        {
            try
            {
                SqlDataStorageEntity entity = null;
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User
                            | IsolatedStorageScope.Assembly, null, null);

                if (isoStore.GetFileNames(name + ".settings").Length == 0)
                {
                    return null;
                }

                Stream stream = new IsolatedStorageFileStream(name + ".settings", FileMode.OpenOrCreate, isoStore);
                if (stream != null)
                {
                    try
                    {
                        IFormatter formatter = new BinaryFormatter();
                        entity = (SqlDataStorageEntity)formatter.Deserialize(stream);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
                return entity;
            }
            catch
            {
                //TODO
            }
            return null;
        }
        #endregion

        #region public static void Save(string name, SqlDataStorageEntity entity)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        public static void Save(string name, SqlDataStorageEntity entity)
        {
            if (entity == null)
            {
                return;
            }
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

            Stream stream = new IsolatedStorageFileStream(name + ".settings", FileMode.Create, isoStore);
            if (stream != null)
            {
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, (SqlDataStorageEntity)entity);
                }
                finally
                {
                    stream.Close();
                }
            }
        }
        #endregion
    }
}
